A good answer might be:

12+4 > 16 5.2-1.2 <= 2.0+22*3-4 == 1+1
false true true

Danger with Comparing Doubles

What do you imagine is the result of evaluating the Boolean expression:

4.0/3.0 == 1.0 + 1.0/3.0

Probably you think that it is true. Probably it is. But not certainly. Floating point arithmetic is not exact. You should never trust an "exactly equals" comparison with floats. The problem is that some numbers require an unlimited number of bits to be represented exactly. For these numbers, even a 64 bit double is not exact.

You are familiar with this situation with paper-and-pencil arithmetic. For example, is the following true?

1.0/3.0 == 0.3333333

It is not true, because the decimal on the right is only an approximation. With more decimal places the approximation gets better, but it is never equal to the fraction. The same occurs with Java (and all other computer programming languages). For example, the following might come out to be false:

1.0/10.0 == 0.1

Sometimes when unquestionable precision is needed, integer arithmetic is used. This is one reason why Java has 64 bit long integers.

QUESTION 5:

What is the output of the following:

import java.io.*;
class DecimalFraction
{
  public static void main (String[] args) throws IOException
  {
    float x = 1.0f;
    float y = 10.0f;
    
    if ( x/y == 0.1 )
      System.out.println("Buy the cookie!"  );
    else
      System.out.println("No cookie for you.");
  }
}